import React from 'react';
import {
  View,
  TouchableOpacity,
  Image,
  Text,
} from 'react-native';
import Video from 'react-native-video';
import Platform from 'Platform';
import Config from '../config';
import SizeUtils from '../common/SizeUtils';
import TComponent from './TComponent';

export default class TVideoComponent extends TComponent {
  constructor(props) {
    super(props);

    // this.props.showClose 是否显示关闭按钮

    this.state.isResponeUpdate = false;
    this.state.paused = false;
    this.state.fullScreen = false;
    this.state.seekableDuration = 0;
    this.state.currentTime = 0;
    this.state.playableDuration = 0;
    this.state.loadState = "";
    this.state.hideBar = false;
    this.state.showTimeMid = false;

    this._videoUrl = this.props.videoUrl;
    this._leave = false;
    this._player = null;
  }

  componentWillUpdate(nextProps, nextState) {
    if(this._videoUrl != nextProps.videoUrl) {
      this._videoUrl = nextProps.videoUrl;
      this._leave = false;
      nextState.hideBar = false;
      this.state.showTimeMid = false;
      this._hideBarTimer();
    }
  }

  _hideBarTimer() {
    this._clearHideBarTimer();
    this._timer = setTimeout(()=>{
     this._clearHideBarTimer()
     this.setState({
       hideBar:true,
       showTimeMid:false,
     })
    }, 5000);
  }

  componentDidMount() {
    this._hideBarTimer();
  }

  componentWillUnmount() {
    this._clearHideBarTimer();
  }

  _clearHideBarTimer() {
    this._timer && clearTimeout(this._timer);
    this._timer = null;
  }

  paused() {
    this._onPressPause();
  }

  render() {
    return(
      <TouchableOpacity style={this._getViewStyle()} onPress={this._onPressBg.bind(this)} activeOpacity = {1}>
        {this._renderVideoComponent()}
        {this._renderLoadState()}
        {this._renderToolsView()}
      </TouchableOpacity>
    )
  }

  _renderToolsView() {
    if(this.state.hideBar === true) {
      return;
    }
    return (
      <TouchableOpacity style={[this._getVideoComponentStyle(),
          {position:"absolute", top:0, left:0, backgroundColor:"#ff00ff00"}]}
          onPress={this._onPressBg.bind(this)} activeOpacity = {1}>
        {this._renderTopBar()}
        {this._renderBottomBar()}
      </TouchableOpacity>
    )
  }

  _renderTimeMiddle() {
    let style = this._getVideoComponentStyle();
    let left = (style.width - SizeUtils.translateDesignWidthToCode(250))/2;
    let top = (style.height - SizeUtils.translateDesignWidthToCode(250))/2;
    return (
      <View style={{width:SizeUtils.translateDesignWidthToCode(200),
          height:SizeUtils.translateDesignWidthToCode(200), borderRadius:SizeUtils.translateDesignNumToCode(10),
          position:"absolute", top:top, left:left, flexDirection:"row", alignItems:"center", justifyContent:"center",
          backgroundColor:"#00000066"}}>
          <Text style={{color:"#ffffff", fontSize:SizeUtils.translateFontSizeToCode(30)}}>
            {this._getCurrentTimeText() + " / " + this._getTotalTimeText()}
          </Text>
      </View>
    )
  }

  _onPressBg() {
    if(this.state.hideBar === true) {
      this._hideBarTimer();
    }
    this.setState({
      hideBar:!this.state.hideBar,
    })
  }

  _getViewStyle() {
    if(Platform.OS === "ios") {
      return this._getViewStyleIOS();
    } else {
      return this._getViewStyleAndroid();
    }
  }

  _renderTopBar() {
    if(this.props.showClose === false) {
      return;
    }
    return (
      <TouchableOpacity onPress={this._onPressClose.bind(this)}
          style={this._getTopBarStyle()}>
          <Image source={require("../../resource/images/common/close.png")} style={{
            marginLeft:SizeUtils.translateDesignWidthToCode(20),
            width:SizeUtils.translateDesignWidthToCode(38), height:SizeUtils.translateDesignWidthToCode(38)
          }}/>
      </TouchableOpacity>
    )
  }

  _getVideoContentStyle() {
    if(this.state.fullScreen) {
      return {
        width:SizeUtils.getWindowSize().height,
        height:SizeUtils.getWindowSize().width,
      };
    }
    else {
      return {
        width:this.props.style.width,
        height:this.props.style.height,
      };
    }
  }

  _getTopBarStyle() {
    if(this.state.fullScreen) {
      return {
        width:SizeUtils.getWindowSize().height,
        height:SizeUtils.translateDesignHeightToCode(100),
        top:SizeUtils.translateDesignWidthToCode(20),
        position:"absolute", left:SizeUtils.translateDesignHeightToCode(30),
      };
    }
    else {
      return {
        width:SizeUtils.translateDesignWidthToCode(100),
        height:SizeUtils.translateDesignHeightToCode(100),
        position:"absolute", top:SizeUtils.translateDesignHeightToCode(20),
      };
    }
  }

  _renderVideoComponent() {
    return(
      <Video source={{uri: this._videoUrl, cache: true}} // Can be a URL or a local file.
       rate={this.state.paused ? 0 : 1.0}                   // 0 is paused, 1 is normal.
       volume={1.0}                 // 0 is muted, 1 is normal.
       muted={false}                // Mutes the audio entirely.
       paused={this.state.paused}               // Pauses playback entirely.
       resizeMode="cover"           // Fill the whole screen at aspect ratio.
       repeat={true}                // Repeat forever.
       onLoadStart={this._loadStart.bind(this)} // Callback when video starts to load
       onLoad={this._setDuration.bind(this)}    // Callback when video loads
       onProgress={this._setTime.bind(this)}    // Callback every ~250ms with currentTime
       onEnd={this._onEnd.bind(this)}           // Callback when playback finishes
       onError={this._videoError.bind(this)}    // Callback when video cannot be loaded
       //  fullScreen={this.state.fullScreen}
       style={this._getVideoComponentStyle()}
       ref={(ref) => {
         this._player = ref
       }} />
    )
  }

  _getVideoComponentStyle() {
    const videoHeight = (this.props.style.width / 2 + SizeUtils.translateDesignHeightToCode(60));
    if(this.state.fullScreen) {
      return {
        width:SizeUtils.getWindowSize().height,
        height:SizeUtils.getWindowSize().height * videoHeight / this.props.style.width,
      };
    }
    else {
      return {
        width:this.props.style.width,
        height:videoHeight,
      };
    }
  }

  _getWidth() {
    if(this.state.fullScreen) {
      return SizeUtils.getWindowSize().height;
    }
    else {
      return this.props.style.width;
    }
  }

  _renderLoadState() {
    return(
      <View style={{position:"absolute", top:this.props.style.height/2, backgroundColor:"#ffffff00"}}>
        <Text style={{color:"#eeeeee", fontSize:SizeUtils.translateFontSizeToCode(20), textAlign:"center",
            width:this._getWidth()}}>
          {this.state.loadState}
        </Text>
      </View>
    )
  }

  _loadStart(event) {
    console.log("_loadStart", event);
    this.setState({
      // loadState:"正在链接视频源:" + event.src.uri,
      loadState:"视频加载中...",
    })
  }

  _setDuration(event) {
    console.log("_setDuration", event);
    this.setState({
      loadState:"",
      seekableDuration:event.duration,
      playableDuration:event.duration
    })
  }

  _setTime(event) {
    // console.log("_setTime", event);
    this.setState({
      // seekableDuration:event.duration,
      currentTime:event.currentTime,
      // playableDuration:event.duration,
    })
  }

  _onEnd(event) {
    console.log("_onEnd", event);
  }

  _videoError(event) {
    console.log("_videoError", event);
    this.setState({
      loadState:"链接视频源出错:" + JSON.stringify(event.error),
    })
  }

  _renderBottomBar() {
    return (
      <View style={{position:"absolute", bottom:0, width:this._getWidth(),
        height:SizeUtils.translateDesignHeightToCode(80), flexDirection:"row", alignItems:"center",
        justifyContent:"center", backgroundColor:"#00000099",}}>
        <View style={{flexDirection:"row", alignItems:"center",
            justifyContent:"center",}}>
          <TouchableOpacity onPress={this._onPressPause.bind(this)} style={{width:SizeUtils.translateDesignWidthToCode(60),
              height:SizeUtils.translateDesignWidthToCode(48),
              paddingRight:SizeUtils.translateDesignWidthToCode(30),
              justifyContent:"center", alignItems:"center"}}>
              {this._renderPauseImage()}
          </TouchableOpacity>
          {this._renderProgress()}
          <TouchableOpacity onPress={this._onPressFull.bind(this)}
            style={{width:SizeUtils.translateDesignWidthToCode(80),
              height:SizeUtils.translateDesignHeightToCode(80),
              paddingLeft:SizeUtils.translateDesignWidthToCode(28),
              flexDirection:"row",
              alignItems:"center"}}>
            <Image source={require('../../resource/images/common/full.png')}
              style={{width:SizeUtils.translateDesignWidthToCode(30),
                height:SizeUtils.translateDesignWidthToCode(30)}}/>
          </TouchableOpacity>
        </View>
      </View>
    )
  }

  _renderProgress() {
    return (
      <View style={{width:this.props.style.width - SizeUtils.translateDesignWidthToCode(160),
          flexDirection:"row", alignItems:"center"}}>
        {this._progressImage()}
        {this._progressText()}
      </View>
    )
  }

  _progressImage() {
    let width = this.props.style.width - SizeUtils.translateDesignWidthToCode(160 + 150);
    return (
      <TouchableOpacity style={{width:width, height:SizeUtils.translateDesignHeightToCode(68),
          flexDirection:"row", alignItems:'center',
          backgroundColor:"#00000000"}} onPress={(event) => this._onPressProgress(event, width)}>
        <View style={{width:width, height:SizeUtils.translateDesignHeightToCode(10),
          // marginTop:SizeUtils.translateDesignHeightToCode((68 - 10)/2),
          backgroundColor:"#ffffff66"}}>
        </View>
        <View style={{width:this.state.playableDuration / this.state.seekableDuration * width,
          height:SizeUtils.translateDesignHeightToCode(10), position:"absolute",
          // top:SizeUtils.translateDesignHeightToCode((68 - 10)/2),
          backgroundColor:"#d0d0ce"}}>
        </View>
        <View style={{width:this.state.currentTime / this.state.seekableDuration * width,
          height:SizeUtils.translateDesignHeightToCode(10), position:"absolute",
          // top:SizeUtils.translateDesignHeightToCode((68 - 10)/2),
          backgroundColor:"#4581fa"}}>
        </View>
        <View style={{position:"absolute", top:0,
            left:this._getPosition()}}>
          <Image source={require("../../resource/images/news/rate.png")} style={{width:SizeUtils.translateDesignWidthToCode(68),
            height:SizeUtils.translateDesignWidthToCode(68)}}/>
        </View>
      </TouchableOpacity>
    )
  }

  _onPressProgress(event, width) {
    this._hideBarTimer();
    this.setState({
      showTimeMid:true,
    })
    console.log(event.nativeEvent.locationX, width);
    if(this._player && this.state.seekableDuration != 0) {
      this._player.seek(event.nativeEvent.locationX/width * this.state.seekableDuration);
    }
  }

  _getPosition() {
    if(this.state.currentTime == 0) {
      return SizeUtils.translateDesignWidthToCode(-24);
    }
    else {
      return SizeUtils.translateDesignWidthToCode(-24 + this.state.currentTime / this.state.seekableDuration * 425);
    }
  }

  _progressText() {
    return (
      <Text style={{fontSize:SizeUtils.translateFontSizeToCode(22), color:"#dcdddf",
          paddingLeft:SizeUtils.translateDesignWidthToCode(20)}}>
        {this._getCurrentTimeText() + " / " + this._getTotalTimeText()}
      </Text>
    )
  }

  _getCurrentTimeText() {
    //soundCurrentTime  单位秒
    return this._getTimeText(this.state.currentTime)
  }

  _getTotalTimeText() {
    //soundTotalTime  单位秒
    return this._getTimeText(this.state.seekableDuration)
  }

  _getTimeText(time) {
    time = Math.ceil(time);
    if(time == 0) {
      return "00:00";
    }
    let minutes = Math.floor(time / 60);
    let second = time - minutes * 60;
    let minutesStr = minutes < 10 ? ("0" + minutes) : minutes;
    let secondStr = second < 10 ? ("0" + second) : second;
    return minutesStr + ":" + secondStr;
  }

  _renderPauseImage() {
    if(this.state.paused) {
      return (
        <Image source={require('../../resource/images/common/bofang2.png')} style={{width:SizeUtils.translateDesignWidthToCode(40),
          height:SizeUtils.translateDesignWidthToCode(40)}}/>
      )
    }
    else {
      return (
        <Image source={require('../../resource/images/common/pause.png')} style={{width:SizeUtils.translateDesignWidthToCode(25),
          height:SizeUtils.translateDesignWidthToCode(48)}}/>
      )
    }
  }

  close() {
    this._onPressClose();
  }

  _onPressClose() {
    if(this.state.fullScreen === false) {
      this._paused();
      this._dealLeave();
    }
    else {
      this._onPressFull();
    }
  }

  _dealLeave() {
    this._videoUrl = "";
    this._leave = true;
    clearTimeout(this._timer);
    this.props.onClose();
  }

  _paused() {
    this.setState({
      paused:true,
    })
  }

  _onPressPause() {
    this._hideBarTimer();
    this.setState({
      paused:!this.state.paused,
    })
  }

  _onPressFull() {
    if(this.props.canFullScreen === false) {
      return;
    }
    if(this.state.fullScreen) {
      // this._player.dismissfullScreenPlayer()
    } else {
      // this._player.presentfullScreenPlayer()
    }
    this.setState({
      fullScreen:!this.state.fullScreen,
      hideBar:false,
    })
  }

  _getViewStyleIOS() {
    if(this.state.fullScreen) {
      return {
        position:"absolute",
        top:0,
        left:0,
        width:SizeUtils.getWindowSize().height,
        height:SizeUtils.getWindowSize().width,
        backgroundColor:"#000000ee",
        flexDirection:"column",
        justifyContent:"center",
        alignItems:"center",
        transform:[{rotate:"-90deg"}, {translateX:SizeUtils.translateDesignHeightToCode(-300)},
          {translateY:SizeUtils.translateDesignWidthToCode(-290)}],
      };
    }
    else {
      return {
        width:this.props.style ? this.props.style.width : SizeUtils.translateDesignWidthToCode(200),
        height:this.props.style ? this.props.style.height : SizeUtils.translateDesignWidthToCode(500),
        backgroundColor:"#000000ee", flexDirection:"column",
        // marginTop:Config.tabBarTop,
        transform:[{rotate:"0deg"}, {translateX:SizeUtils.translateDesignHeightToCode(0)},
          {translateY:SizeUtils.translateDesignWidthToCode(0)}]
      };
    }
  }

  _getViewStyleAndroid() {
    if(this.state.fullScreen) {
      return {
        position:"absolute",
        top:0,
        left:0,
        width:SizeUtils.getWindowSize().height,
        height:SizeUtils.getWindowSize().width,
        backgroundColor:"#000000ee",
        flexDirection:"column",
        justifyContent:"center",
        alignItems:"center",
        transform:[{translateX:SizeUtils.translateDesignHeightToCode(-240)},
          {translateY:SizeUtils.translateDesignWidthToCode(220)}, {rotate:1.57}],
      };
    }
    else {
      return {
        width:this.props.style ? this.props.style.width : SizeUtils.translateDesignWidthToCode(200),
        height:this.props.style ? this.props.style.height + SizeUtils.translateDesignHeightToCode(60) : SizeUtils.translateDesignWidthToCode(500),
        backgroundColor:"#000000ee", flexDirection:"column",
        marginTop:Config.tabBarTop,
        transform:[{rotate:0}, {translateX:SizeUtils.translateDesignHeightToCode(0)},
          {translateY:SizeUtils.translateDesignWidthToCode(0)}]
      };
    }
  }
}
